#!/usr/bin/env python
# -*- coding: utf-8 -*-

import ansible.runner
from ansible.inventory import Inventory
import os
import sys
import time
import httplib, urllib, urllib2
import json
import requests

# construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
    pattern='10.200.*', forks=10,
    module_name='setup', module_args='',
).run()

if results is None:
   print "No hosts found"
   sys.exit(1)
h={}
print "UP ***********"
for (hostname, result) in results['contacted'].items():
    if not 'failed' in result:
        print hostname
        h[hostname] = {}
        h[hostname]['ip'] = hostname
        h[hostname]['status'] = 'on_line'
        sn = result['ansible_facts']['ansible_product_serial']
        if sn and sn != 'NA':
            h[hostname]['sn'] = result['ansible_facts']['ansible_product_serial']
        else:
            h[hostname]['sn'] = 'None_' + str(time.time())

        h[hostname]['vendor'] = result['ansible_facts']['ansible_system_vendor'] + ' ' + result['ansible_facts']['ansible_product_name']
        biz = result['ansible_facts']['ansible_nodename'].split('.')[-1]
        ip_host = '-'.join(hostname.split('.'))
        h[hostname]['description'] = 'YG-bigdata.hadoop-' + biz + '.' + ip_host
        nic = ''
        mac = ''
        for netcard in result['ansible_facts']['ansible_interfaces']:
            if netcard != 'lo':
                ncd = result['ansible_facts']['ansible_'+netcard]
                if 'device' in ncd:
                    nic = nic + ncd['device']
                if 'ipv4' in ncd:
                    nic = nic + ' #ip: ' + ncd['ipv4']['address']
                if 'macaddress' in ncd:
                    nic = nic + ' #mac: ' + ncd['macaddress'] + ' ; '
                    mac = mac + ncd['macaddress'] + ','
        h[hostname]['nic'] = nic
        h[hostname]['hostname'] = 'YG-bigdata.hadoop-' + biz + '.' + ip_host
        out_ip = []
        for i in result['ansible_facts']['ansible_all_ipv4_addresses']:
            if i.find('10.100.') < 0:
                out_ip.append(i)
        h[hostname]['ip_out'] = ','.join(out_ip)
        cpu_process = ''.join(result['ansible_facts']['ansible_processor'][1:2])
        cpu_num = result['ansible_facts']['ansible_processor_count']
        cpu_core = result['ansible_facts']['ansible_processor_cores']
        cpu_threads = result['ansible_facts']['ansible_processor_threads_per_core']
        cpu_vcpus = result['ansible_facts']['ansible_processor_vcpus']
        h[hostname]['cpu'] = cpu_process + " (" + str(cpu_num) + 'cpu * ' + str(cpu_core) + 'cores * ' + str(cpu_threads) + 'threads = ' + str(cpu_vcpus) + 'vcpus)'
        h[hostname]['idc_id'] = 77
        h[hostname]['mac'] = mac
        h[hostname]['rnode_id'] = 17
        mem = int(round(result['ansible_facts']['ansible_memtotal_mb'] / 1000.0))
        h[hostname]['memory'] = str(mem) + "G"
        h[hostname]['host_id'] = 0
        if 'ansible_lsb' in result['ansible_facts']:
            h[hostname]['os'] = result['ansible_facts']['ansible_lsb']['description'] + ' ' + result['ansible_facts']['ansible_kernel']


print h.values()

url = 'http://rms.ops.hunantv.com/api/server/create?token=a43fe51e9b6991583a8be305deb00b40'
#url = 'http://10.1.172.98:8001/api/server/create?token=33c00b44f17658fe98d72fca3c2845c2'
headers = {"Content-type": "application/json"}
"""
params = h.values()
conn = urllib2.Request(url, json.dumps(params), headers)

#headers = {"Content-type": "application/json",
#        "Accept": "text/plain"}
#conn = httplib.HTTPConnection("rms.ops.hunantv.com")
#conn.request("POST", "/api/server/create?token=a43fe51e9b6991583a8be305deb00b40", params, headers)
#conn = httplib.HTTPConnection("www.yftest.com")
#conn.request("POST", "/?token=a43fe51e9b6991583a8be305deb00b40", params, headers)
#response = conn.getresponse()
response = urllib2.urlopen(conn)
print response.read()
"""
r = requests.post(url, data=json.dumps(h.values()), headers=headers)
print r.status_code, r.text

print "FAILED *******"
for (hostname, result) in results['contacted'].items():
    if 'failed' in result:
        print "%s >>> %s" % (hostname, result['msg'])

print "DOWN *********"
for (hostname, result) in results['dark'].items():
    print "%s >>> %s" % (hostname, result)
